// API 服务配置
const API_BASE_URL = 'http://admin-yzy-two.wudkmao.top/api/v1';

// 获取存储的token
const getToken = () => {
  return uni.getStorageSync('token') || '';
};

// 设置token
const setToken = (token) => {
  uni.setStorageSync('token', token);
};

// 清除token
const clearToken = () => {
  uni.removeStorageSync('token');
};

// 构建查询字符串（兼容小程序）
const buildQueryString = (params) => {
  const queryParts = [];
  for (const key in params) {
    if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
      queryParts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
    }
  }
  return queryParts.length > 0 ? `?${queryParts.join('&')}` : '';
};

// 通用请求方法
const request = async (url, options = {}) => {
  const token = getToken();
  
  const defaultOptions = {
    url: `${API_BASE_URL}${url}`,
    header: {
      'Content-Type': 'application/json',
      ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
      ...options.header
    },
    ...options
  };

  return new Promise((resolve, reject) => {
    uni.request({
      ...defaultOptions,
      success: (res) => {
        if (res.statusCode === 200 || res.statusCode === 201) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // token过期，跳转登录
          clearToken();
          uni.reLaunch({ url: '/pages/login/index' });
          reject(new Error('认证失败'));
        } else {
          reject(new Error(res.data?.message || '请求失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

// 认证相关API
export const authAPI = {
  // 用户登录
  login: (username, password, rememberMe = false) => {
    return request('/auth/login', {
      method: 'POST',
      data: { 
        Username: username, 
        Password: password,
        RememberMe: rememberMe
      }
    });
  },
  
  // 用户注册
  register: (userData) => {
    return request('/auth/register', {
      method: 'POST',
      data: userData
    });
  },
  
  // 获取用户信息
  getUserInfo: () => {
    return request('/auth/user');
  },
  
  // 退出登录
  logout: () => {
    clearToken();
    uni.reLaunch({ url: '/pages/login/index' });
  }
};

// 文档管理API
export const documentAPI = {
  // 上传文档 - 完全按照后端DocumentController接口设计
  upload: (file, progressCallback = null, fileName = null) => {
    return new Promise((resolve, reject) => {
      const token = getToken();
      
      if (!token) {
        reject(new Error('未找到认证token，请先登录'));
        return;
      }

      // #ifdef H5
      // H5端：使用FormData和fetch
      if (file.originalFile && file.originalFile instanceof File) {
        // 验证文件
        if (file.originalFile.size === 0) {
          reject(new Error('文件大小为0，请选择有效的文件'));
          return;
        }
        
        // 验证是否为文件夹
        if (file.originalFile.size === 0 && !file.originalFile.name.includes('.')) {
          reject(new Error('不能上传文件夹，请选择文件'));
          return;
        }
        
        const formData = new FormData();
        formData.append('file', file.originalFile);
        
        // 如果提供了fileName，添加到FormData中
        if (fileName) {
          formData.append('fileName', fileName);
        }
        
        console.log('H5端上传 - 文件:', file.originalFile);
        console.log('H5端上传 - 文件名:', fileName || file.name);
        console.log('H5端上传 - FormData内容:');
        for (let [key, value] of formData.entries()) {
          console.log(`${key}:`, value);
        }

        // H5端模拟进度（因为fetch不支持进度）
        if (progressCallback) {
          let progress = 0;
          const progressInterval = setInterval(() => {
            progress += Math.random() * 20;
            if (progress >= 100) {
              progress = 100;
              clearInterval(progressInterval);
            }
            progressCallback(progress);
          }, 100);
        }

        fetch(`${API_BASE_URL}/document/upload`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            // 不要手动设置Content-Type，让浏览器自动设置multipart/form-data的boundary
          },
          body: formData,
        })
        .then(response => {
          console.log('上传响应状态:', response.status);
          console.log('上传响应头:', response.headers);
          
          if (response.status === 201) {
            // 成功：201 Created
            return response.json();
          } else if (response.ok) {
            // 其他成功状态码
            return response.json();
          } else {
            // 失败状态码
            return response.text().then(text => {
              throw new Error(`上传失败 (${response.status}): ${text}`);
            });
          }
        })
        .then(data => {
          console.log('上传成功，返回数据:', data);
          if (progressCallback) progressCallback(100);
          resolve(data);
        })
        .catch(error => {
          console.error('H5端上传失败:', error);
          reject(error);
        });
        return;
      }
      // #endif
      
      // 非H5端或没有originalFile的情况：使用uni.uploadFile
      let filePath = file.path || file.tempFilePath || file.tempPath;
      
      if (!filePath) {
        reject(new Error(`文件路径无效，请检查文件选择方式。平台：${process.env.UNI_PLATFORM}`));
        return;
      }
      
      console.log('非H5端上传 - 文件路径:', filePath);
      console.log('非H5端上传 - 文件名:', fileName || file.name);
      
      const uploadTask = uni.uploadFile({
        url: `${API_BASE_URL}/document/upload`,
        filePath: filePath,
        name: 'file',
        formData: {
          // 如果提供了fileName，添加到formData中
          ...(fileName && { fileName: fileName })
        },
        header: {
          'Authorization': `Bearer ${token}`,
          // 不要手动设置Content-Type，让uni-app自动设置
        },
        success: (res) => {
          console.log('uni.uploadFile响应:', res);
          
          if (res.statusCode === 201) {
            // 成功：201 Created
            try {
              const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
              if (progressCallback) progressCallback(100);
              resolve(data);
            } catch (e) {
              reject(new Error('服务器响应格式错误'));
            }
          } else if (res.statusCode >= 200 && res.statusCode < 300) {
            // 其他成功状态码
            try {
              const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
              if (progressCallback) progressCallback(100);
              resolve(data);
            } catch (e) {
              reject(new Error('服务器响应格式错误'));
            }
          } else {
            // 失败状态码
            try {
              const errorData = JSON.parse(res.data);
              reject(new Error(errorData.message || `上传失败 (${res.statusCode})`));
            } catch (e) {
              reject(new Error(`上传失败 (${res.statusCode}): ${res.data}`));
            }
          }
        },
        fail: (error) => {
          console.error('uni.uploadFile失败:', error);
          reject(new Error(error.errMsg || '网络错误'));
        }
      });
      
      // 监听上传进度（微信小程序端）
      if (uploadTask && uploadTask.onProgressUpdate && progressCallback) {
        uploadTask.onProgressUpdate((res) => {
          console.log('上传进度:', res.progress + '%');
          progressCallback(res.progress);
        });
      }
    });
  },
  
  // 获取文档列表
  getList: (page = 1, pageSize = 10, keyword = '') => {
    const params = {
      page: page.toString(),
      pageSize: pageSize.toString()
    };
    if (keyword) params.keyword = keyword;
    
    return request(`/document${buildQueryString(params)}`);
  },
  
  // 获取文档详情
  getDetail: (id) => {
    return request(`/document/${id}`);
  },
  
  // 删除文档
  delete: (id) => {
    return new Promise((resolve, reject) => {
      const token = getToken();
      
      uni.request({
        url: `${API_BASE_URL}/document/${id}`,
        method: 'DELETE',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          console.log('删除文档响应:', res);
          if (res.statusCode === 204) {
            // 204 No Content 表示删除成功
            resolve({ success: true });
          } else if (res.statusCode === 401) {
            // token过期，跳转登录
            clearToken();
            uni.reLaunch({ url: '/pages/login/index' });
            reject(new Error('认证失败，请重新登录'));
          } else if (res.statusCode === 404) {
            reject(new Error('文档不存在或无权限删除'));
          } else if (res.statusCode === 400) {
            const errorMsg = res.data?.message || '删除失败';
            reject(new Error(errorMsg));
          } else {
            reject(new Error('删除失败'));
          }
        },
        fail: (err) => {
          console.error('删除文档请求失败:', err);
          reject(new Error(err.errMsg || '网络错误'));
        }
      });
    });
  },
  
  // 获取文档分块信息
  getChunks: (id, page = 1, pageSize = 10) => {
    const params = {
      page: page.toString(),
      pageSize: pageSize.toString()
    };
    
    return request(`/document/${id}/chunks${buildQueryString(params)}`);
  },
  
  // 重新索引文档
  reindex: (id) => {
    return request(`/document/${id}/reindex`, { method: 'POST' });
  }
};

// 聊天相关API
export const chatAPI = {
  // 创建对话
  createConversation: (title) => {
    return request('/chat/conversation', {
      method: 'POST',
      data: { Title: title }
    });
  },
  
  // 获取对话列表
  getConversations: (page = 1, pageSize = 10) => {
    const params = {
      page: page.toString(),
      pageSize: pageSize.toString()
    };
    
    return request(`/chat/conversations${buildQueryString(params)}`);
  },
  
  // 发送问题
  askQuestion: (question, conversationId) => {
    return request('/chat/ask', {
      method: 'POST',
      data: { Question: question, ConversationId: conversationId }
    });
  },
  
  // 获取对话历史
  getHistory: (conversationId) => {
    return request(`/chat/conversation/${conversationId}/history`);
  },
  
  // 删除对话
  deleteConversation: (id) => {
    return new Promise((resolve, reject) => {
      const token = getToken();
      
      uni.request({
        url: `${API_BASE_URL}/chat/conversation/${id}`,
        method: 'DELETE',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          console.log('删除对话响应:', res);
          if (res.statusCode === 204 || res.statusCode === 200) {
            // 204 No Content 或 200 OK 都表示删除成功
            resolve({ success: true });
          } else if (res.statusCode === 401) {
            // token过期，跳转登录
            clearToken();
            uni.reLaunch({ url: '/pages/login/index' });
            reject(new Error('认证失败，请重新登录'));
          } else if (res.statusCode === 404) {
            reject(new Error('对话不存在或无权限删除'));
          } else if (res.statusCode === 400) {
            const errorMsg = res.data?.message || '删除失败';
            reject(new Error(errorMsg));
          } else {
            reject(new Error('删除失败'));
          }
        },
        fail: (err) => {
          console.error('删除对话请求失败:', err);
          reject(new Error(err.errMsg || '网络错误'));
        }
      });
    });
  }
};

export { getToken, setToken, clearToken };